package com.ruoyi.framework.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author abel lee
 * asdtiangxia@163.com tel:18190910296   qq:250753635
 * @create 2023-10-20 09:02
 **/
@Component
public class JSessionIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        if (request instanceof HttpServletRequest
                && response instanceof HttpServletResponse) {

            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            // 从URL中移除JSESSIONID
            if (httpRequest.isRequestedSessionIdFromURL()) {
                String url = httpRequest.getRequestURI();
                String session = httpRequest.getRequestedSessionId();
                url = url.replaceAll(";jsessionid=" + session, "");
                httpResponse.sendRedirect(url);
                return;
            }
        }

        chain.doFilter(request, response);
    }
}